
package at.fhj.ase.clientarch.server.component;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.fhj.ase.clientarch.common.HardwareData;
import at.fhj.ase.clientarch.common.TransferObject;
import at.fhj.ase.clientarch.common.component.IHardwareComponent;
import at.fhj.ase.clientarch.common.exception.BizException;
import at.fhj.ase.clientarch.common.util.CollectionUtil;
import at.fhj.ase.clientarch.server.db.dao.impl.DatabaseController;
import at.fhj.ase.clientarch.server.db.hibernate.entities.EntityHardwareData;
import at.fhj.ase.clientarch.server.sigar.SigarController;

/**
 * @author cja, sfe | www.fh-joanneum.at | Client Architectures and Design
 * @see IHardwareComponent
 */
public class HardwareComponentImpl extends AbstractComponent implements IHardwareComponent, Serializable {
  private static final long serialVersionUID = 3485606874920091378L;
  private Logger logger = LoggerFactory.getLogger(getClass().getName());

  HardwareComponentImpl() throws RemoteException {
    super();
  }

  @Override
  public Properties getConfig() throws RemoteException, BizException {
    return RMIController.INSTANCE.getClientConfig();
  }

  @Override
  public TransferObject getCurrentData() throws RemoteException, BizException {
    final TransferObject serverDataObject = new TransferObject();
    serverDataObject.addHardwareData(SigarController.INSTANCE.getCurrentData());
    logger.debug("Data list transfering to client: " + serverDataObject.getDataList());
    return serverDataObject;
  }

  @Override
  public TransferObject getDataFromDB(Timestamp start, Timestamp end) throws RemoteException, BizException {
    final List<EntityHardwareData> hardwareDataList = DatabaseController.INSTANCE.getHardwareDataDao().findByTimestamp(start, end);
    if (CollectionUtil.isNullOrEmpty(hardwareDataList)) {
      return null;
    }

    final TransferObject newTransferObject = new TransferObject();
    for (EntityHardwareData hwData : hardwareDataList) {
      final HardwareData newHardwareData = new HardwareData(hwData.getCpu(), hwData.getRam(), hwData.getTimestamp());
      newTransferObject.addHardwareData(newHardwareData);
    }

    return newTransferObject;
  }
}
